﻿using CPPEI.Coolzon.Designer.Views;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DT = CPPEI.Coolzon.Designtime.Metadata;
using CPPEI.Coolzon.Metadata;
using System.IO;

namespace CPPEI.Coolzon.Designtime
{
    public class DesignerDataSourceTool : IDataSourcePool
    {
        public ServiceProxy.DesignServiceRef.PublishedDataSource[] GetDataSources()
        {
            ServiceProxy.DesignServiceRef.DesignServiceClient client = ServiceProxy.DesignServiceProxyManager.Create();

            ServiceProxy.DesignServiceRef.GetPublishedDataSourceListRequest request = new ServiceProxy.DesignServiceRef.GetPublishedDataSourceListRequest(UIContext.Current.CurrentSolution.ID,
                UIContext.Current.Token);
            ServiceProxy.DesignServiceRef.ListResultOf_PublishedDataSource dataSources = client.GetPublishedDataSources(request);

            if(dataSources.IsSuccess)
            {
                return dataSources.Data;
            }
            return null;
        }

        public string GetStaticDataSource(string name)
        {
            DT.Solution dtSolution = UIContext.Current.CurrentSolution;
            for (int index = 0; index < dtSolution.StaticDataSources.Count; index++)
            {
                if (string.Equals(dtSolution.StaticDataSources[index].Name, name))
                {
                    try
                    {
                        return File.ReadAllText(DT.LocalStorage.GetStaticDataSourceAbsolutePath(UIContext.Current.LocalWorkSpace.LocalPath, dtSolution.ID, dtSolution.StaticDataSources[index].Id));
                    }
                    catch (Exception ex)
                    {
                        return null;
                    }
                }
            }
            return null;
        }

        public StaticDataSource[] GetStaticDataSources()
        {
            List<StaticDataSource> list = new List<StaticDataSource>();
            DT.Solution dtSolution = UIContext.Current.CurrentSolution;
            for (int index = 0; index < dtSolution.StaticDataSources.Count; index++)
            {
                list.Add(dtSolution.StaticDataSources[index].RT_StaticDataSource);
            }
            return list.ToArray();
        }
    }
}
